package com.sqx.modules.toppingConfig.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sqx.common.utils.DateUtils;
import com.sqx.common.utils.Result;
import com.sqx.modules.app.entity.UserMoney;
import com.sqx.modules.app.entity.UserMoneyDetails;
import com.sqx.modules.app.service.UserMoneyDetailsService;
import com.sqx.modules.app.service.UserMoneyService;
import com.sqx.modules.app.service.UserService;
import com.sqx.modules.postPush.entity.PostPush;
import com.sqx.modules.postPush.service.PostPushService;
import com.sqx.modules.toppingConfig.entity.ToppingConfig;
import com.sqx.modules.toppingConfig.dao.ToppingConfigDao;
import com.sqx.modules.toppingConfig.service.IToppingConfigService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sun.org.apache.regexp.internal.RE;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * <p>
 * 置顶时长配置 服务实现类
 * </p>
 *
 * @author wuchang
 * @since 2023-07-27
 */
@Service
public class ToppingConfigServiceImpl extends ServiceImpl<ToppingConfigDao, ToppingConfig> implements IToppingConfigService {

    @Autowired
    private PostPushService postPushService;
    @Autowired
    private UserMoneyService userMoneyService;
    @Autowired
    private UserMoneyDetailsService detailsService;
    private final ReentrantReadWriteLock reentrantReadWriteLock = new ReentrantReadWriteLock(true);
    @Override
    public Result saveConfig(ToppingConfig config) {
        if (config.getConfigId() != null) {
            return Result.upStatus(baseMapper.updateById(config));
        } else {
            config.setCreateTime(LocalDateTime.now());
            return Result.upStatus(baseMapper.insert(config));
        }
    }

    @Override
    public IPage<ToppingConfig> getConfigList(Integer page, Integer limit, ToppingConfig config) {
        Page<ToppingConfig> pages;
        if (page != null && limit != null) {
            pages = new Page<>(page, limit);
        } else {
            pages = new Page<>();
            pages.setSize(-1);
        }

        return baseMapper.selectPage(pages, new QueryWrapper<>(config).orderByAsc("sort"));

    }

    @Override
    public Result buyTopping(Long userId, Long postPushId, Long configId) {
        reentrantReadWriteLock.writeLock().lock();
        try {
            ToppingConfig config = baseMapper.selectById(configId);
            if (config == null || config.getIsEnable() == 0) {
                return Result.error("所选时长不存在或未启用");
            }
            PostPush postPush = postPushService.getById(postPushId);
            if (postPush.getStatus() != 1) {
                return Result.error("当前状态无法购买置顶");
            }
            UserMoney userMoney = userMoneyService.getOne(new QueryWrapper<UserMoney>().eq("user_id", userId));
            if (userMoney.getMoney().compareTo(new BigDecimal(config.getIntegral())) < 0) {
                return Result.error("你的积分不足,请充值后再试!");
            }
            userMoneyService.updateMoney(2, userId, new BigDecimal(config.getIntegral()));
            UserMoneyDetails moneyDetails = new UserMoneyDetails();
            moneyDetails.setUserId(userId);
            moneyDetails.setType(2);
            moneyDetails.setMoney(new BigDecimal(config.getIntegral()));
            moneyDetails.setTitle("购买置顶");
            moneyDetails.setContent("购买置顶" + config.getHour() + "小时成功");
            moneyDetails.setClassify(2);
            moneyDetails.setState(2);
            moneyDetails.setCreateTime(DateUtils.format(new Date()));
            detailsService.save(moneyDetails);
            //到期时间为null,或者已到期都用当前时间加小时数
            if (postPush.getTopEndTime() == null || postPush.getTopEndTime().compareTo(LocalDateTime.now()) <= 0) {
                postPush.setTopEndTime(LocalDateTime.now().plusHours(config.getHour()));
            } else {
                postPush.setTopEndTime(postPush.getTopEndTime().plusHours(config.getHour()));
            }
            postPush.setIsTop(1);
            return postPushService.updateById(postPush) ? Result.success() : Result.error();
        }catch (Exception e){
            e.printStackTrace();
            log.error("购买异常：" + e.getMessage(), e);
        } finally {
            reentrantReadWriteLock.writeLock().unlock();
        }
       return Result.error("购买失败,请重试!");
    }
}
